<?php
/**
 * Created by PhpStorm.
 * User: renbin
 * 功能: 处理用户银行卡号
 * Date: 2015/6/8
 * Time: 9:59
 */
namespace common\models\Service;
use common\models\Cache;
use common\models\CommonFunction;
use common\models\CommonVar;
use common\models\DAO\DayAccrual;
use common\models\DAO\HongbaoSendList;
use common\models\DAO\Product;
use common\models\DAO\TeamBrokerage;
use common\models\DAO\User;
use common\models\DAO\UserCharge;
use common\models\DAO\UserIdentity;
use common\models\DAO\UserWalletLog;
use common\models\LLpay\LLpayConfig;
use common\models\LLpay\LLpaySubmit;
use common\msg\UserMsg;
use yii\base\Exception;

class UserCard {

    //用户id
    public $userID;
    /**
     * @param array $userID 用户id
     */
    public function __construct($userID = null){
        if($userID)
            $this->userID = $userID;
    }

    /*
     * 用户银行卡信息以及用户的身份证、手机号
     */
    public function init(){
        $userID = $this->userID;
        $result = array();

        /*//获取身份证号码
        $userInfo = \common\models\DAO\User::findOne($userID);
        if(isset($userInfo['identity']) && !empty($userInfo['identity']) ){

            $result['userInfo'] = $userInfo->attributes;
        }*/
        //获取用户银行卡号
        $bankCard = \common\models\DAO\UserCard::find()->where(array('userID'=>$userID))->orderBy('updateTime desc, id desc')->all();
        if($bankCard){
            $cardInfo = array();
            foreach($bankCard as $v){
                $card = $v->attributes;
                if(isset($card['card'])){
                    $cardInfo_cur['card'] = substr(CommonFunction::decrypt($card['card'], CommonVar::$encrypt), -4);
                    //银行编码对应银行
                    $bankCode = CommonVar::$bank_code;
                    if(isset($card['bankCode']) && isset($bankCode[$card['bankCode']])){
                        $cardInfo_cur['bankCode'] = $card['bankCode'];
                        $cardInfo_cur['bank'] = $bankCode[$card['bankCode']]['name'];
                        $cardInfo_cur['bank_id'] = CommonFunction::encrypt($card['id']);
                    }
                    $cardInfo[] = $cardInfo_cur;
                }
            }
            $result['card'] = $cardInfo;
        }


        if(!isset($result['card'])){
            //获取身份证号码
            $userInfo = User::findOne($userID);
            if($userInfo)
                $userInfo = $userInfo->attributes;
            if(isset($userInfo['identity']) && !empty($userInfo['identity']) ){
                $result['userInfo'] = $userInfo;
            }
        }

        //获取用户绑定手机号

        return $result;
    }

    /**
     * @param $parame充值提供参数
     * @return bool
     */
    public function deal($parame, $source = 2){
        $parame['name_goods'] = UserMsg::$charge;
        $parame['pay_type'] = 'D';

        $userID = $this->userID;
        $return['status'] = 0;
        $return['msg'] = UserMsg::$time_out;

        if($parame['money_order'] <= 0){
            $return['msg'] = '充值金额不能小于0元。';
            return $return;
        }
        //获取银行卡号
        if(isset($parame['bank_code']) && isset($parame['bank_id'])){
            $cardInfo = \common\models\DAO\UserCard::findOne(array('bankCode'=>$parame['bank_code'], 'userID'=>$userID, 'id'=>CommonFunction::decrypt($parame['bank_id'])));
            if(!$cardInfo)
                return $return;
            $cardInfo = $cardInfo->attributes;
            if(!$cardInfo['card'])
                return $return;
            if($cardInfo['no_agree'])
                $parame['no_agree'] = CommonFunction::decrypt($cardInfo['no_agree'], CommonVar::$encrypt);
            $parame['card_no'] = CommonFunction::decrypt($cardInfo['card'], CommonVar::$encrypt);
        }

        $encrypt = CommonVar::$encrypt;
        $userModel = User::findOne($userID);

        $userInfo = $userModel->attributes;
        //商户订单号
        $no_order = CommonFunction::buildOrder();
        //商户网站订单系统中唯一订单号，必填
        $now = time();
        $transaction = \Yii::$app->db->beginTransaction();
        try{
            //系统添加订单
            $userCharge = new UserCharge();
            $userCharge->userID = $userID;
            $userCharge->createTime = $now;
            $userCharge->sourceID = $source;
            $userCharge->money = doubleval($parame['money_order']) * 100;
            $userCharge->card = CommonFunction::encrypt($parame['card_no'], $encrypt);
            $userCharge->order = $no_order;
            $charge_result = $userCharge->save();
            if(!$charge_result){
                $transaction->rollBack();
                return $return;
            }

            //验证身份信息
            if(!$userInfo['identity'] || !$userInfo['realName']){
                if(!isset($parame['id_no']) || !isset($parame['acct_name'])){
                    $return['msg'] = UserMsg::$no_name_card;
                    return $return;
                }else if(strstr($parame['id_no'], 'X'))
                    $parame['id_no'] = strtolower($parame['id_no']);

                $identity = CommonFunction::encrypt($parame['id_no'], $encrypt);

                //验证身份证是否已经被使用
                $is_reg = UserIdentity::find()->where(array('identity'=>$identity))->andFilterWhere(['!=', 'userID', $userID])->all();
                if($is_reg){
                    $return['msg'] = UserMsg::$use_card;
                    return $return;
                }

                //身份认证
                $identityModel = new UserIdentity();
                $identityModel->userID = $userID;
                $identityModel->identity = $identity;
                $identityModel->realName = $parame['acct_name'];
                $identityModel->orderID = $userCharge->id;
                $identity_result = $identityModel->save();
                if(!$identity_result){
                    $transaction->rollBack();
                    return $return;
                }
            }else{
                $parame['id_no'] = CommonFunction::decrypt($userInfo['identity'], CommonVar::$encrypt);
                $parame['acct_name'] = $userInfo['realName'];
            }

            $transaction->commit();
        }catch (Exception $e){
            $transaction->rollBack();
            return $return;
        }
        /**************************请求参数 start**************************/

        //商户用户唯一编号
        $user_id = CommonFunction::encrypt('scyd'.$userID, CommonVar::$encrypt);
        //支付类型
        $busi_partner = LLpayConfig::$busi_partner;

        //付款金额
        $money_order = $parame['money_order'];
        //必填

        //商品名称
        $name_goods = $parame['name_goods'];

        //支付方式
        $pay_type = $parame['pay_type'];

        //卡号
        $card_no = $parame['card_no'];

        //姓名
        $acct_name = $parame['acct_name'];

        //身份证号
        $id_no = $parame['id_no'];

        //{"frms_ware_category":"2009","user_info_mercht_userno":"13165753886","user_info_dt_register":"20150605122130",
        //"user_info_full_name":"张逢春","user_info_id_no":"610303198602124816","user_info_identify_state":0,"user_info_identify_type":1}

        //风险控制参数
        $risk_item = '{"frms_ware_category":"2009","user_info_mercht_userno":"'.$user_id.'","user_info_dt_register":"'.date('YmdHis',$userInfo['createTime']).'","user_info_full_name":"'.$parame['acct_name'].'","user_info_id_no":"'.$parame['id_no'] .'","user_info_identify_state":0,"user_info_identify_type":1}';
        //服务器异步通知页面路径
        $notify_url = LLpayConfig::$notify_url;
        //需http://格式的完整路径，不能加?id=123这类自定义参数

        //页面跳转同步通知页面路径
        $return_url = LLpayConfig::$return_url;
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

        /**************************请求参数 end**************************/

        date_default_timezone_set('PRC');
        $llpay_config = LLpayConfig::getConfig();
        //构造要请求的参数数组，无需改动
        $parameter = array (
            "version" => trim($llpay_config['version']),
            "oid_partner" => trim($llpay_config['oid_partner']),
            "sign_type" => trim($llpay_config['sign_type']),
            "userreq_ip" => trim($llpay_config['userreq_ip']),
            "id_type" => trim($llpay_config['id_type']),
            "valid_order" => trim($llpay_config['valid_order']),
            "user_id" => $user_id,
            "timestamp" => date('YmdHis', $now),
            "busi_partner" => $busi_partner,
            "no_order" => $no_order,
            "dt_order" => date('YmdHis', $now),
            "name_goods" => $name_goods,
            "money_order" => $money_order,
            "notify_url" => $notify_url,
            "url_return" => $return_url,
            "pay_type" => $pay_type,
            "risk_item" => $risk_item,
            "id_no" => $id_no,
            "acct_name" => $acct_name,
            "card_no" => $card_no,
        );

        //协议号
        if(isset($parame['no_agree'])){
            $parameter['no_agree'] = $parame['no_agree'];
        }
        header("Content-type: text/html; charset=utf-8");
        $llpaySubmit = new LLpaySubmit($llpay_config);
        //建立请求
        $html_text = $llpaySubmit->buildRequestForm($parameter, "post", "确认");
        return $html_text;
    }

    /**
     * @param $no_order 订单号
     * @param $bank_code 银行编号
     * @return mixed
     */
    public function dealReturn($no_order, $bank_code, $no_agree = '', $sourceID = 1){
        //二次交易协议加密
        if($no_agree)
            $no_agree = CommonFunction::encrypt($no_agree, CommonVar::$encrypt);
        $return['status'] = 0;
        $return['msg'] = UserMsg::$time_out;
        /*
         * 事务start
         */
        $transaction = \Yii::$app->db->beginTransaction();
        try{
            //用户订单信息
            $order = UserCharge::findOne(array('order'=>$no_order));
            if(!$order){
                $return['msg'] = UserMsg::$call_center;
                return $return;
            }

            $now = time();
            $order_info = $order->attributes;

            //用户id
            if(!$order_info['userID'])
                return $return;
            $userID = $order_info['userID'];

            //银行卡号
            if(!$order_info['card'])
                return $return;
            $bank_card = $order_info['card'];

            if($order_info['status'] == 1){
                $return['status'] = 1;
                $return['msg'] = UserMsg::$charge_sucess;
                //添加用户绑定银行卡
                $cardModel = \common\models\DAO\UserCard::findOne(array('userID'=>$userID, 'card'=>$bank_card));
                if($cardModel){
                    $cardModel->updateTime = $now;
                    $card_info = $cardModel->attributes;
                    if(empty($bank_code))
                        return $return;

                    if($no_agree && empty($card_info['no_agree'])){
                        $cardModel->no_agree = $no_agree;
                        $cardModel->save();
                    }
                }else{
                    $cardModel = new \common\models\DAO\UserCard();
                    $cardModel->userID = $userID;
                    $cardModel->createTime = $now;
                    $cardModel->card = $bank_card;
                    $cardModel->updateTime = $now;
                    if(!empty($bank_code)){
                        $cardModel->bankCode = $bank_code;
                        if($no_agree){
                            $cardModel->no_agree = $no_agree;
                        }
                        $cardModel->save();
                    }
                }
                $transaction->commit();
                return $return;
            }
            //更新订单状态
            $order->status = 1;
            $order->updateTime = $now;
            $order_result = $order->save();
            if(!$order_result){
                $transaction->rollBack();
                return $return;
            }
            //更新用户身份证信息
            $userModel = User::findOne($userID);
            $userInfo = $userModel->attributes;
            $date = date('Ymd');
            $chargeInfo = \common\models\DAO\UserCard::find()->where("userID=$userID")->count();
            if($chargeInfo == 0 && !empty($userInfo['recID'])){
                $rec_info = User::findOne($userInfo['recID']);
                if($rec_info){
                    $hb_flag = HongbaoSendList::findOne(['sendUserID'=>$userInfo['recID'],'userID'=>$userID]);

                    $is_accrual = DayAccrual::findOne(['userID'=>$userInfo['recID'], 'sendUserID'=>$userID]);
                    if(!$is_accrual && $hb_flag){
                        $money = 300;
                        $dayAccrual = new DayAccrual();
                        $dayAccrual->userID = $rec_info['id'];
                        $dayAccrual->date = $date;
                        $dayAccrual->money = $money;
                        $dayAccrual->invest = $money;
                        $dayAccrual->createTime = $now;
                        $dayAccrual->updateTime = $now;
                        $dayAccrual->sendID = $hb_flag->sendID;
                        $dayAccrual->sendUserID = $userID;
                        $accrual_result  = $dayAccrual->save();
                        if(!$accrual_result) {
                            $transaction->rollBack();
                            return $return;
                        }
                        //钱包明细
                        $rec_wallet = new UserWalletLog();
                        $rec_wallet->type = 8;
                        $rec_wallet->money = $money;
                        $rec_wallet->createTime = $now;
                        $rec_wallet->userID = $rec_info['id'];
                        $rec_wallet->road = 1;
                        $rec_wallet->desc = '新用户'.CommonFunction::dealTel(CommonFunction::decrypt($userInfo['phone'])).'领取红包奖励';
                        $rec_wallet_result = $rec_wallet->save();
                        if(!$rec_wallet_result) {
                            $transaction->rollBack();
                            return $return;
                        }

                        $team_brokerage = new TeamBrokerage();
                        $team_brokerage->investID = 0;
                        $team_brokerage->productID = 0;
                        $team_brokerage->userID = $rec_info['id'];
                        $team_brokerage->investUserID = $userID;
                        $team_brokerage->money = 0;
                        $team_brokerage->brokerage = $money;
                        $team_brokerage->rate = 0;
                        $team_brokerage->createTime = $now;
                        $team_brokerage->userInvestID = 0;
                        $brokerage_result = $team_brokerage->save();
                        if(!$brokerage_result) {
                            $transaction->rollBack();
                            return $return;
                        }
                        if(!empty($rec_info['openID'])){
                            SendWxMessage::charge($rec_info['openID'], CommonFunction::formatMoney($money), '您的好友'.CommonFunction::dealTel(CommonFunction::decrypt($userInfo['phone'])).'绑定银行卡，您获得了'.CommonFunction::formatMoney($money).'元！');
                        }
                    }

                }
            }
            /*$chargeInfo = \common\models\DAO\UserCard::find()->where("userID=$userID")->count();
            if($chargeInfo == 0 && !empty($userInfo['recID'])){
                $recInfo = User::findOne($userInfo['recID']);
                if(!empty($recInfo) && Wallet::remainder($userInfo['recID']) >= 1000){
                    $frist_money = 100;
                    $dayAccrual = new DayAccrual();
                    $dayAccrual->userID = $recInfo['id'];
                    $dayAccrual->date = $date;
                    $dayAccrual->money = $frist_money;
                    $dayAccrual->invest = $frist_money;
                    $dayAccrual->createTime = $now;
                    $dayAccrual->updateTime = $now;
                    $dayAccrual->stairID = $userID;
                    $dayAccrual->chargeID = 0;
                    $accrual_result  = $dayAccrual->save();
                    if(!$accrual_result){
                        $transaction->rollBack();
                        return $return;
                    }
                    //钱包明细
                    $user_wallet = new UserWalletLog();
                    $user_wallet->type = 1;
                    $user_wallet->money = $frist_money;
                    $user_wallet->createTime = $now;
                    $user_wallet->userID = $recInfo['id'];
                    $user_wallet->road = 10;
                    $user_wallet->desc = '好友'.CommonFunction::dealTel(CommonFunction::decrypt($userInfo['phone'])).'绑定银行卡';
                    $user_wallet_result = $user_wallet->save();
                    if(!$user_wallet_result){
                        $transaction->rollBack();
                        return $return;
                    }
                    $team_brokerage = new TeamBrokerage();
                    $team_brokerage->investID = 0;
                    $team_brokerage->productID = 0;
                    $team_brokerage->userID = $recInfo['id'];
                    $team_brokerage->investUserID = $userID;
                    $team_brokerage->money = 0;
                    $team_brokerage->brokerage = $frist_money;
                    $team_brokerage->rate = 0;
                    $team_brokerage->createTime = $now;
                    $team_brokerage->userInvestID = 0;
                    $team_brokerage->userInvestID = 0;
                    $brokerage_result = $team_brokerage->save();
                    if(!$brokerage_result){
                        $transaction->rollBack();
                        return $return;
                    }
                    if(!empty($recInfo['openID'])){
                        SendWxMessage::charge($recInfo['openID'], CommonFunction::formatMoney($frist_money), '您的好友'.CommonFunction::dealTel(CommonFunction::decrypt($userInfo['phone'])).'绑定银行卡，您获得了'.CommonFunction::formatMoney($frist_money).'元佣金！');
                    }
                    if($recInfo['recID']){
                        $secondaryInfo = User::findOne($recInfo['recID']);
                        if(!empty($secondaryInfo)){
                            $second_money = 50;
                            $dayAccrual = new DayAccrual();
                            $dayAccrual->userID = $secondaryInfo['id'];
                            $dayAccrual->date = $date;
                            $dayAccrual->money = $second_money;
                            $dayAccrual->invest = $second_money;
                            $dayAccrual->createTime = $now;
                            $dayAccrual->updateTime = $now;
                            $dayAccrual->stairID = $userID;
                            $dayAccrual->secondaryID = $userID;
                            $dayAccrual->chargeID = 0;
                            $accrual_result  = $dayAccrual->save();
                            if(!$accrual_result){
                                $transaction->rollBack();
                                return $return;
                            }
                            //钱包明细
                            $user_wallet = new UserWalletLog();
                            $user_wallet->type = 1;
                            $user_wallet->money = $second_money;
                            $user_wallet->createTime = $now;
                            $user_wallet->userID = $secondaryInfo['id'];
                            $user_wallet->road = 10;
                            $user_wallet->desc = '好友'.CommonFunction::dealTel(CommonFunction::decrypt($userInfo['phone'])).'邀请'.CommonFunction::dealTel(CommonFunction::decrypt($recInfo['phone'])).'绑定银行卡';
                            $user_wallet_result = $user_wallet->save();
                            if(!$user_wallet_result){
                                $transaction->rollBack();
                                return $return;
                            }
                            $team_brokerage = new TeamBrokerage();
                            $team_brokerage->investID = 0;
                            $team_brokerage->productID = 0;
                            $team_brokerage->userID = $secondaryInfo['id'];
                            $team_brokerage->investUserID = $userID;
                            $team_brokerage->money = 0;
                            $team_brokerage->brokerage = $second_money;
                            $team_brokerage->rate = 0;
                            $team_brokerage->createTime = $now;
                            $team_brokerage->userInvestID = 0;
                            $team_brokerage->userInvestID = 0;
                            $brokerage_result = $team_brokerage->save();
                            if(!$brokerage_result){
                                $transaction->rollBack();
                                return $return;
                            }
                            if(!empty($secondaryInfo['openID'])){
                                SendWxMessage::charge($secondaryInfo['openID'], CommonFunction::formatMoney($second_money), '您的好友'.CommonFunction::dealTel(CommonFunction::decrypt($userInfo['phone'])).'邀请好友绑定银行卡，您获得了'.CommonFunction::formatMoney($second_money).'元佣金！');
                            }
                        }

                    }

                }

            }*/
            //更新用户账号余额
            $dayAccrual = new DayAccrual();
            $dayAccrual->userID = $userID;
            $dayAccrual->date = $date;
            $dayAccrual->money = $order_info['money'];
            $dayAccrual->invest = $order_info['money'];
            $dayAccrual->createTime = $now;
            $dayAccrual->updateTime = $now;
            $dayAccrual->chargeID = $order->id;
            $accrual_result  = $dayAccrual->save();
            if(!$accrual_result){
                $transaction->rollBack();
                return $return;
            }
            //钱包明细
            $user_wallet = new UserWalletLog();
            $user_wallet->type = 1;
            $user_wallet->money = $order_info['money'];
            $user_wallet->createTime = $now;
            $user_wallet->userID = $userID;
            $user_wallet->road = 1;
            $user_wallet_result = $user_wallet->save();
            if(!$user_wallet_result){
                $transaction->rollBack();
                return $return;
            }
            if(empty($userInfo['identity']) || empty($userInfo['realName'])){
                $identityModel = UserIdentity::findOne(array('orderID'=>$order_info['id']));
                if($identityModel){
                    $identity_info = $identityModel->attributes;
                    $userModel->identity = $identity_info['identity'];
                    $user_id_info = CommonFunction::id_no_deal($identity_info['identity']);
                    $userModel->sex = $user_id_info['sex'];
                    $userModel->age = $user_id_info['age'];
                    $userModel->realName = $identity_info['realName'];
                    $user_result = $userModel->save();
                    if(!$user_result){
                        $transaction->rollBack();
                        return $return;
                    }
                    UserIdentity::deleteAll('userID = :userID AND orderID != :orderID', [':userID' => $userID, ':orderID' => $order_info['id']]);
                }
            }

            //添加用户绑定银行卡
            $cardModel = \common\models\DAO\UserCard::findOne(array('userID'=>$userID, 'card'=>$bank_card));
            if($cardModel){
                $cardModel->updateTime = $now;
                $card_info = $cardModel->attributes;
                $card_result = true;
                if($no_agree && empty($card_info['no_agree'])){
                    $cardModel->no_agree = $no_agree;
                    $card_result = $cardModel->save();
                }

            }else{
                $cardModel = new \common\models\DAO\UserCard();
                $cardModel->userID = $userID;
                $cardModel->createTime = $now;
                $cardModel->card = $bank_card;
                $cardModel->updateTime = $now;
                $card_result = true;
                if(!empty($bank_code)){
                    $cardModel->bankCode = $bank_code;
                    if($no_agree){
                        $cardModel->no_agree = $no_agree;
                    }
                    $card_result = $cardModel->save();
                }
            }
            if(!$card_result){
                $transaction->rollBack();
                return $return;
            }

            //用户日志
            $user_log = UserLog::set(['userID'=>$userID, 'money'=>$order_info['money'],
                'chargeID'=>$order_info['id'], 'sourceID'=>$sourceID, 'desc'=>'充值']);
            if(!$user_log){
                $transaction->rollBack();
                return $return;
            }

            $product = Product::findOne(1);
            $product->person = intval($product['person']) + 1;
            $product->money = intval($order_info['money']) + intval($product['money']);
            $product_result = $product->save();
            if(!$product_result){
                $transaction->rollBack();
                return $return;
            }
            $cache_name = 'product_1';
            $cache = Cache::get($cache_name);
            if($cache){
                $cache['money'] = $product['money'];
                $cache['person'] = $product['person'];
                Cache::set($cache_name, $cache);
            }

            //事务提交
            $transaction->commit();
            $return['status'] = 1;
            $return['msg'] = UserMsg::$charge_sucess;
            if(!empty($userInfo['openID'])){
                SendWxMessage::charge($userInfo['openID'], CommonFunction::formatMoney($order_info['money']));
            }
            return $return;
        }catch (Exception $e){
            $transaction->rollBack();
            return $return;
        }
        /*
        * 事务end
        */

    }
}